package com.followmeandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.followmeandroid.enums.PrintFriend;
import com.followmeandroid.enums.ResultCode;
import com.followmeandroid.enums.ServiceUrl;
import com.followmeandroid.messages.DeleteFriendRequest;
import com.followmeandroid.models.CurrentMember;
import com.followmeandroid.models.Friend;
import com.followmeandroid.util.FollowMeSharedPreferences;
import com.followmeandroid.util.JSONHttpClient;


/**
 * <p>Title: FriendProfileActivity</p>
 * <p>Description: This activity controls the content and
 * functionality of the Friend Profile screen.</p>
 * @author Nicholas Thorp
 * @email nicholas.thorp@my.uwrf.edu
 * @date 11/30/2014
 * @team Adam Drews
 * @email adam.drews@my.uwrf.edu
 * @team Tyler Johnson
 * @email tyler.johnson@my.uwrf.edu
 */
public class FriendProfileActivity extends Activity {

    Context thisContext;
    private TextView tvFriendEmail, tvFriendName;
    private Button btnMessage, btnLocation, btnDelete;
    Friend friend;

    /**
     * Creates the layout for the current view. It is passed a
     * bundle of data from the previous activity.
     * @param savedInstanceState        The state of the previous activity.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_profile);
        thisContext = this;
        Intent intent = getIntent();
        friend = (Friend)intent.getSerializableExtra("passedFriend");

        tvFriendEmail = (TextView)findViewById(R.id.tvFriendEmail);
        tvFriendName = (TextView)findViewById(R.id.tvFriendName);
        tvFriendEmail.setText(friend.getEmail());
        friend.setPrint(PrintFriend.NAME);
        tvFriendName.setText(friend.toString());
        //Change the Friend setPrint() back to the default email address
        friend.setPrint(PrintFriend.EMAIL);

        btnMessage = (Button)findViewById(R.id.buttonMessageFriend);
        btnLocation = (Button)findViewById(R.id.buttonFriendLocation);
        btnDelete = (Button)findViewById(R.id.buttonDeleteFriend);

        btnMessage.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                //TODO  open message activity
            }
        });

        btnLocation.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                //TODO send location request
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteFriend(friend);
            }
        });
    }

    /**
     * Creates the options menu on the action bar.
     * @param menu      The menu to be used.
     * @return true     Success!
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_friend_profile, menu);
        return true;
    }

    /**
     * Controls the action when a menu  item is clicked.
     * @param item          The item that was clicked.
     * @return  true        Success!
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * This method will delete the given friend from the member's friends
     * list, and remove them from the friend list view.
     * @param friend            The friend to be removed.
     */
    protected void deleteFriend(final Friend friend) {
        DeleteFriendRequest deletefriend = new DeleteFriendRequest(friend.getFriendID().toString());

        new AsyncTask<DeleteFriendRequest, JSONHttpClient, Integer>(){

            /**
             * The operation to be performed by the thread in the background.
             * @param params        A delete friend request.
             * @return result       The result from the request.
             */
            @Override
            protected Integer doInBackground (DeleteFriendRequest...params){
                Integer result = 0;

                try {
                    // Call delete, delete friends.
                    result = JSONHttpClient.Delete(ServiceUrl.DELETE_FRIEND.toString(), params[0].toKeyValuePairs());

                } catch (Exception e) {
                    Log.d("AsyncDeleteFriend", e.getMessage());
                }
                return result;
            }

            /**
             * Displays a please wait pop up before the thread executes.
             */
            @Override
            protected void onPreExecute () {

                super.onPreExecute();
                Toast.makeText(thisContext, "Please Wait...", Toast.LENGTH_SHORT).show();
            }

            /**
             * Displays the result from trying to delete the friend. This result is determined
             * be a result code received by the server.
             * @param result        The failure or success of the action.
             */
            @Override
            protected void onPostExecute (Integer result){
                //result is http result code, 200 = OK
                if (ResultCode.get(result) == ResultCode.OK) {
                    CurrentMember.getMember().deleteFriend(friend);
                    //friends.remove(friend);
                    FollowMeSharedPreferences.saveMember();

                    Toast.makeText(thisContext, friend.getUserName() + " deleted!", Toast.LENGTH_LONG).show();
                } else {
                    //make them try again!
                    Toast.makeText(thisContext, "Friend not found, or you are no longer friends!", Toast.LENGTH_LONG).show();
                }
                //setUpFriendsList(CurrentMember.getMember().getFriends());
                finish();
            }
        }.execute(deletefriend);
    }
}
